var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var config = require('../config/db')
const mongdb = require('mongodb')
var passport = require('passport')    //1.导入认证模块
const jwt = require('jsonwebtoken')

//加入购物车
router.post('/addCart',passport.authenticate('jwt',{session:false}),async function(req,res,next){
    let product = req.body.product//获取加入购物车所需要商品信息
    let client = await MongoClient.connect(config.url) //获取数据库连接对象
    let db = client.db()
    let newCart = {
        "userId":req.user._id,
        "product":product,
        "num":1,
        "addTime":new Date()
    }
    let results = await db.collection('carts').insertOne(newCart)
    console.log('results:',results)
    //判断是否添加成功
    if(results.acknowledged){
        res.json({code:200,message:'ok'});
    }else{
        res.json({code:200,message:'error'});
    }
})

//显示购物车
router.get('/getCarts',passport.authenticate('jwt',{session:false}),async function(req,res,next){
    let client = await MongoClient.connect(config.url) //获取数据库连接对象
    let db = client.db()
    let products = await db.collection('carts').find({userId:req.user._id}).sort({'addTime':-1}).toArray()
    console.log('carts',products)
    //判断是否添加成功
    if(products.length >= 0){
        res.json({code:200,message:'ok',data:products});
    }else{
        res.json({code:200,message:'error'});
    }
});
 // 删除购物车
 router.delete('/deleteCart',passport.authenticate('jwt',{session:false}),async function(req,res,next){
     let {id}= req.query                  //获取需要删除的购物车信息id
     let client = await MongoClient.connect(config.url) // 获取数据库连接对象 
     let db = client.db()
    let results = await db.collection('carts').deleteOne({_id:new mongdb.ObjectId(id)})// 执行删除购物车的操作
    console.log('results:',results)
     //判断是否删除成功
     if(results.acknowledged){
         res.json({code:200,message:'ok'});
    }else{
        res.json({code:200,message:'error'});
     }
    
    })

    router.delete('/deleteCarts',passport.authenticate('jwt',{session:false}),async function(req,res,next){
        let {ids}= req.query  //获取需要删除的购物车信息id
        let objIds = []
        ids.map(id => {
            objIds.push(new mongdb.ObjectId(id))
        })
        let client = await MongoClient.connect(config.url) // 获取数据库连接对象 
        let db = client.db()
        let results = await db.collection('carts').deleteMany({_id:{$in:objIds}})// 执行删除购物车的操作
        console.log('results:',results)
        //判断是否删除成功
        if(results.acknowledged){
         res.json({code:200,message:'ok'});
         }else{
         res.json({code:200,message:'error'});
         }
        });

module.exports = router
